<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../res/layui/css/layui.css">
    <style>
        #userInfoDialog {
            padding: 20px;
            width: 400px;
            display: none; /*隐藏层*/
        }

        #userInfoDialog p {
            padding: 10px 0;
        }
    </style>


</head>
<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">歌单列表</div>
        <div class="layui-card-body">
            <table id="musiclist" lay-filter="musiclistFilter"></table>
        </div>
    </div>
</div>

<!--歌单详情对话框-->
<div id="details" style="display: none;padding: 20px">
    <div style="margin-bottom: 15px; text-align: right">
        <button id="addMusicBtn" class="layui-btn layui-btn-warm">
            <i class="layui-icon layui-icon-add-circle"></i> 添加音乐
        </button>
    </div>
    <table class="layui-table" lay-skin="nob">
        <tr>
            <td rowspan="3">
                <img src="" id="coverimg" height="96px" alt="">
            </td>
            <td colspan="2">
                <h2><span id="listname"></span></h2>
                <span><i class="layui-icon layui-icon-username"></i><span id="create"></span></span>
            </td>
        </tr>
        <tr>
            <td colspan="2">标签: <span id="tags"></span></td>
        </tr>
        <tr>
            <td>点击量: <span id="clickcount"></span></td>
            <td>歌曲总数: <span id="musiccount"></span></td>
        </tr>
    </table>

    <!-- 专辑详情表-->
    <table id="musiclistDetails"></table>
</div>

<script src="../res/layui/layui.js"></script>
<script src="../js/music-player.js"></script>
<script>
    layui.use(function () {
        //加载获取table模块
        var table = layui.table;
        //加载获取layer弹层模块
        var layer = layui.layer;
        //加载jquery对象
        var $ = layui.jquery;
        
        //渲染歌单列表表格
        table.render({
            elem: '#musiclist',
            url: '/musicList/list',
            toolbar: '#toolbar',
            where: {}, //搜索条件
            page: true,
            cols: [[
                {field: 'id', title: 'ID', width: 80},
                {field: 'name', title: '歌单名称', minWidth: 150},
                {field: 'createBy', title: '创建者', width: 100},
                {field: 'tags', title: '标签', minWidth: 120},
                {field: 'clickCount', title: '点击量', width: 80},
                {field: 'musicCount', title: '歌曲数量', width: 80},
                {field: 'createTime', title: '创建时间', width: 160, templet: function(d) {
                    return layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss');
                }},
                {title: '操作', width: 180, templet: '#rowTools', fixed: 'right'}
            ]]
        });
    
    // 音乐上传弹窗内容已在页面中直接实现，通过跳转到music-add.html
        
        //监听表格头部工具条事件
        table.on('toolbar(musiclistFilter)', function(obj) {
            if (obj.event === 'add') {
                // 跳转到歌单添加页面
                window.location.href = 'musiclist-add.html';
            } else if (obj.event === 'search') {
                //获取搜索关键字
                var keyword = $('#keyword').val().trim();
                //重新加载表格数据
                table.reload('musiclist', {
                    where: {
                        keyword: keyword
                    },
                    page: {
                        curr: 1 //重新从第1页开始
                    }
                });
            }
        });
        
        //监听表格工具栏事件
        table.on('tool(musiclistFilter)', function(obj) {
            var data = obj.data;
            if (obj.event === 'details') {
                //查看详情
                layer.open({
                    type: 1,
                    title: '歌单详情',
                    content: $('#details'),
                    area: ['800px', '500px'],
                    success: function(layero) {
                        // 设置歌单ID到对话框元素
                        $(layero).find('#details').data('musicListId', data.id);
                    }
                });
                //填充详情数据
                $('#coverimg').attr('src', data.coverImg || '../res/img/default_cover.jpg');
                $('#listname').text(data.name);
                $('#create').text(data.createBy);
                $('#tags').text(data.tags);
                $('#clickcount').text(data.clickCount);
                $('#musiccount').text(data.musicCount);
                
                // 保存当前歌单ID
                $('#details').data('musicListId', data.id);
                
                // 绑定添加音乐按钮事件
                $('#addMusicBtn').off('click').on('click', function() {
                    var musicListId = $('#details').data('musicListId');
                    // 打开选择音乐弹窗
                    layer.open({
                        type: 2,
                        title: '从歌曲库选择音乐',
                        content: 'select-music.html?type=musiclist&id=' + musicListId,
                        area: ['800px', '600px'],
                        success: function(layero, index) {
                            // 保存当前弹窗索引，以便选择完成后关闭
                            window.currentSelectMusicIndex = index;
                        }
                    });
                });
                
                //加载歌单详情中的歌曲列表
                table.render({
                    elem: '#musiclistDetails',
                    url: '/musicListDetails/getByMusicListId?id=' + data.id,
                    page: false,
                    cols: [[
                        {field: 'id', title: 'ID', width: 80},
                        {field: 'musicName', title: '歌曲名称', minWidth: 200},
                        {field: 'singer', title: '歌手', width: 120},
                        {field: 'duration', title: '时长', width: 80, templet: function(d) {
                            //格式化时长
                            var minutes = Math.floor(d.duration / 60);
                            var seconds = d.duration % 60;
                            return minutes + ':' + (seconds < 10 ? '0' + seconds : seconds);
                        }},
                        {title: '播放', width: 80, templet: '#playButton'},
                        {title: '操作', width: 80, templet: function(d) {
                            return '<a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs" onclick="removeMusicFromList(' + d.id + ',' + data.id + ')">删除</a>';
                        }}
                    ]]
                });
            } else if (obj.event === 'edit') {
                //编辑操作
                window.location.href = 'musiclist-add.html?id=' + data.id;
            } else if (obj.event === 'del') {
                //删除操作
                layer.confirm('确定要删除这个歌单吗？', function(index) {
                    $.get('/musicList/delete', {id: data.id}, function(resp) {
                        if (resp.code === 0) {
                            layer.msg('删除成功', {icon: 1});
                            obj.del();
                        } else {
                            layer.msg(resp.msg || '删除失败', {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            }
        });
    })
</script>


<!--操作栏自定义模板-->
<script id="rowTools" type="text/html">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal layui-btn-xs" lay-event="details">
            <i class="layui-icon layui-icon-more"></i>
            详情
        </button>
        <button class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i>
            修改
        </button>
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
            <i class="layui-icon layui-icon-delete"></i>
            删除
        </button>
    </div>
</script>

<!--工具栏模板-->
<script id="toolbar" type="text/html">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i>添加歌单
        </button>
        <div class="layui-input-inline" style="width: 200px">
            <input type="text" class="layui-input" id="keyword" placeholder="请输入查询关键字">
        </div>
        <button class="layui-btn layui-btn-normal" lay-event="search">
            <i class="layui-icon layui-icon-search"></i>
            搜索
        </button>
    </div>
</script>
    
    <script>
    layui.use(['table', 'jquery', 'layer'], function() {
        var table = layui.table;
        var $ = layui.jquery;
        var layer = layui.layer;
        
        // 从歌单中移除歌曲
        window.removeMusicFromList = function(detailId, musicListId) {
            layer.confirm('确定要从歌单中移除这首歌曲吗？', function(index) {
                $.ajax({
                    type: 'post',
                    url: '/musicListDetails/delete',
                    data: {id: detailId},
                    success: function(resp) {
                        if (resp.code === 0) {
                            layer.msg('移除成功', {icon: 1});
                            // 重新加载歌曲列表
                            table.render({
                                elem: '#musiclistDetails',
                                url: '/musicListDetails/getByMusicListId?id=' + musicListId,
                                page: false,
                                cols: [[
                                    {field: 'id', title: 'ID', width: 80},
                                    {field: 'musicName', title: '歌曲名称', minWidth: 200},
                                    {field: 'singer', title: '歌手', width: 120},
                                    {field: 'duration', title: '时长', width: 80, templet: function(d) {
                                        //格式化时长
                                        var minutes = Math.floor(d.duration / 60);
                                        var seconds = d.duration % 60;
                                        return minutes + ':' + (seconds < 10 ? '0' + seconds : seconds);
                                    }},
                                    {title: '播放', width: 80, templet: '#playButton'},
                                    {title: '操作', width: 80, templet: function(d) {
                                        return '<a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs" onclick="removeMusicFromList(' + d.id + ',' + musicListId + ')">删除</a>';
                                    }}
                                ]]
                            });
                        } else {
                            layer.msg(resp.msg || '移除失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络请求失败，请检查服务器状态', {icon: 2});
                    }
                });
                layer.close(index);
            });
        };
    });
    </script>


<!--播放按钮模板-->
<script id="playButton" type="text/html">
    <button class="layui-btn layui-btn-normal layui-btn-xs preview-btn" lay-event="playOrPause" data-playing="0">
        <i class="layui-icon layui-icon-play"></i>
    </button>
</script>

<script>
    //监听歌单详情中歌曲列表的播放按钮点击事件
    layui.use(['table', 'jquery', 'layer'], function() {
        var table = layui.table;
        var $ = layui.jquery;
        var layer = layui.layer;
        
        //监听表格工具事件
        table.on('tool(musiclistDetails)', function(obj) {
            var data = obj.data;
            var button = $(this);
            if (obj.event === 'playOrPause') {
                // 处理播放按钮点击事件
                if (window.MusicPlayer) {
                    // 获取当前按钮
                    var button = $(this);
                    var isPlaying = button.attr('data-playing') === '1';
                    
                    // 检查数据对象结构
                    console.log('歌曲数据:', data);
                    
                    // 首先尝试直接从data对象中获取URL
                    var songUrl = data.url || data.path || data.musicUrl;
                    
                    // 创建音乐数据对象
                    var musicData = {
                        name: data.musicName,
                        singer: data.singer,
                        url: songUrl
                    };
                    
                    // 检查当前点击的歌曲是否就是正在播放的歌曲
                    var isCurrentSong = false;
                    if (songUrl && window.MusicPlayer.getCurrentMusic) {
                        var currentMusic = window.MusicPlayer.getCurrentMusic();
                        if (currentMusic && currentMusic.url) {
                            // 比较文件名来判断是否是同一首歌
                            var currentFileName = currentMusic.url.split('/').pop();
                            var clickedFileName = songUrl.split('/').pop();
                            isCurrentSong = currentFileName === clickedFileName;
                        }
                    }
                    
                    if (isCurrentSong) {
                        // 如果是正在播放的歌曲，切换播放/暂停状态
                        MusicPlayer.togglePlayPause();
                    } else {
                        // 播放新歌曲
                        if (songUrl) {
                            // 获取当前歌单详情页面的所有音乐数据作为播放列表
                            var musicTable = table.cache['musiclistDetails'] || [];
                            var playList = musicTable.map(function(item) {
                                return {
                                    name: item.musicName,
                                    singer: item.singer,
                                    url: item.url || item.path || item.musicUrl
                                };
                            });
                            
                            // 调用MusicPlayer播放音乐并设置播放列表
                            MusicPlayer.play(musicData, playList);
                        } else {
                            // 如果没有URL，尝试获取歌曲详情
                            var musicId = data.musicId || data.id;
                            if (musicId) {
                                $.ajax({
                                    type: 'get',
                                    url: '/music/getById?id=' + musicId,
                                    success: function(resp) {
                                        if (resp.code === 0 && resp.data) {
                                            var url = resp.data.url || resp.data.path;
                                            if (url) {
                                                musicData.url = url;
                                                
                                                // 获取当前歌单详情页面的所有音乐数据作为播放列表
                                                var musicTable = table.cache['musiclistDetails'] || [];
                                                var playList = musicTable.map(function(item) {
                                                    return {
                                                        name: item.musicName,
                                                        singer: item.singer,
                                                        url: item.url || item.path || item.musicUrl
                                                    };
                                                });
                                                
                                                // 调用MusicPlayer播放音乐并设置播放列表
                                                MusicPlayer.play(musicData, playList);
                                            } else {
                                                layer.msg('当前歌曲暂无播放链接', {icon: 2});
                                            }
                                         } else {
                                            layer.msg('获取歌曲信息失败', {icon: 2});
                                         }
                                    },
                                    error: function() {
                                        layer.msg('网络请求失败', {icon: 2});
                                    }
                                });
                            } else {
                                layer.msg('歌曲ID不存在', {icon: 2});
                            }
                        }
                    }
                }
            }
        });
        
        // 使用URL播放音乐
        function playWithUrl(musicData, songData, button) {
            // 获取当前歌单中的所有歌曲作为播放列表
            var musicTable = table.cache['musiclistDetails'] || [];
            var playList = [];
            
            // 构建播放列表
            musicTable.forEach(function(item) {
                playList.push({
                    name: item.musicName,
                    singer: item.singer,
                    url: item.url || item.path || item.musicUrl || ''
                });
            });
            
            // 调用MusicPlayer播放音乐并设置播放列表
            MusicPlayer.play(musicData, playList);
            
            // 更新按钮状态
            var isPlaying = button.attr('data-playing') === '1';
            if (isPlaying) {
                button.attr('data-playing', '0');
                button.find('i').removeClass('layui-icon-pause').addClass('layui-icon-play');
                MusicPlayer.togglePlayPause();
            } else {
                button.attr('data-playing', '1');
                button.find('i').removeClass('layui-icon-play').addClass('layui-icon-pause');
            }
            
            // 确保所有播放按钮状态正确更新
            setTimeout(() => {
                if (window.MusicPlayer && window.MusicPlayer.updateTableButtons) {
                    window.MusicPlayer.updateTableButtons();
                }
            }, 100);
        }
    });
    
    // 当页面加载完成后，更新播放按钮状态
    $(function() {
        // 确保播放器已初始化
        if (window.MusicPlayer && window.MusicPlayer.updateTableButtons) {
            // 延迟执行以确保播放器完全加载
            setTimeout(() => {
                window.MusicPlayer.updateTableButtons();
            }, 500);
        }
    });
</script>
</body>
</html>